﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using d1Common.WebController;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using d1Common;
using d1Project.Tools;
using d1Project.Modules.Common.do4A.Models;

namespace d1Project.Modules.Common.do4A.Controllers.a1
{
    [Route("do4A/a1/MyPassword")]
    public class MyPasswordController : Authorize1Controller
    {
        protected override DbContext dbContext
        {
            get
            {
                return this.db;
            }
        }
        private do4ADbContext db = new do4ADbContext();

        public async Task<IHttpActionResult> Put(MyPasswordGetVm model)
        {
            if (!ModelState.IsValid) this.Error("新密码不能为空");

            var _user1 = await db.User1s.FindAsync(this.UserId);
            if (_user1 == null) this.Error("用户不存在");

            var entity = await db.User1Pwds.FindAsync(this.UserId);
            if (entity == null)
            {
                User1Pwd user1Pwd = new User1Pwd();
                user1Pwd.Id = this.UserId;
                user1Pwd.Password = model.Password;
                db.User1Pwds.Add(user1Pwd);
            }
            else
            {
                entity.Password = model.Password;
            }
            await db.SaveChangesAsync();
            return Ok();
        }
    }

    public class MyPasswordGetVm
    {
        [Required]
        public string Password { get; set; }
    }
}